import basicAuth from 'basic-auth';
import jwt from 'jsonwebtoken';
import { Forbidden, config } from 'lin-mizar';

class Auth {
  constructor (level) {
    this.level = level || 1;
  }
  static USER = 8;
  static ADMIN = 16;
  static SUPER_ADMIN = 32;


  get m () {
    return async (ctx, next) => {
      const userToken = basicAuth(ctx.req);
      let errMsg = 'token不合法';
      if (process.env.NODE_ENV === 'development') {
        ctx.auth = {
          uid: 2,
          // uid: 17,
          // uid: 22,
          scope: 1
        };

        await next();
        return;
      }
      if (!userToken || !userToken.name) {
        throw new Forbidden({ message: errMsg });
      }
      try {
        const secret = config.getItem('secret');
        var decode = jwt.verify(
          userToken.name,
          secret
        );
      } catch (error) {
        if (error.name === 'TokenExpiredError') {
          errMsg = 'token已过期';
        }
        throw new Forbidden({ message: errMsg });
      }

      if (decode.scope < this.level) {
        errMsg = '权限不足';
        throw new Forbidden({ message: errMsg });
      }

      // uid,scope
      ctx.auth = {
        uid: decode.uid,
        scope: decode.scope
      };

      await next();
    };
  }

  static verifyToken (token) {
    try {
      const secret = config.getItem('secret');
      jwt.verify(token,
        secret);
      return true;
    } catch (error) {
      return false;
    }
  }

  static generateToken (uid, scope) {
    const secretKey = config.getItem('secret');
    const expiresIn = config.getItem('expiresIn');
    const token = jwt.sign({
      uid,
      scope
    }, secretKey, {
      expiresIn
    });
    return token;
  };
}

module.exports = {
  Auth
};